#include "groupchat.h"
#include "ui_groupchat.h"
#include <QTimer>
#include <QDateTime>
GroupChat::GroupChat(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GroupChat),
    socket(new QTcpSocket(this)) // 移动socket的创建到构造函数初始化列表中
{
    ui->setupUi(this);
    this->setWindowTitle("群聊");
    ui->MessageEdit->setReadOnly(true);
    connect(socket, &QTcpSocket::connected, this, &GroupChat::onConnected);
    connect(socket, &QTcpSocket::readyRead, this, &GroupChat::onReadyRead);
    connect(ui->SendBtn, &QPushButton::clicked, this, &GroupChat::on_SendBtn_clicked);
    connect(ui->CloseBtn, &QPushButton::clicked, this, &GroupChat::on_CloseBtn_clicked);
    connect(socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &GroupChat::onError);

    socket->connectToHost("192.168.1.45", 8080);
}
GroupChat::~GroupChat()
{
    delete ui;
    socket->deleteLater(); // 使用deleteLater来安全地删除socket
}

void GroupChat::onConnected()
{
    qDebug() << "连接成功";
}

void GroupChat::onReadyRead()
{
    QByteArray data = socket->readAll();
    QString message = QString::fromUtf8(data);
//    appendMessage("Server: " + message, Qt::AlignLeft, Qt::blue);
    //qDebug() << "收到数据：" << data;
    // 假设服务器发送的消息以特殊标记区分，如"USERLIST:"标记用户列表
       if (message.startsWith("USERLIST:"))
       {
           updateUserList(message);
       }
       else
       {
           appendMessage("Server", message, Qt::AlignLeft, Qt::blue);
       }
       //qDebug() << "收到数据：" << data;
}




void GroupChat::on_CloseBtn_clicked()
{
    this->close();
}


void GroupChat::on_SendBtn_clicked()
{
    QString message = ui->SendEdit->toPlainText();
    if (!message.isEmpty())
    {
        QDateTime currentTime = QDateTime::currentDateTime();
        QString timeString = currentTime.toString("hh:mm:ss");
        QString formattedMessage = "[" + timeString + "] " + message;
        socket->write(formattedMessage.toUtf8() + "\n");
        appendMessage("You", message, Qt::AlignRight, Qt::red);
        ui->SendEdit->clear();
    }
}
void GroupChat::appendMessage(const QString &sender, const QString &message, Qt::Alignment alignment, const QColor &textColor)
{
    QTextCursor cursor = ui->MessageEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->MessageEdit->setTextCursor(cursor);

    QTextBlockFormat blockFormat;
    blockFormat.setAlignment(alignment);
    QTextCharFormat charFormat;
    charFormat.setForeground(QBrush(textColor)); // 设置文本颜色
    cursor.mergeCharFormat(charFormat);
    cursor.insertBlock(blockFormat);
    // 获取当前时间
    // 插入发送者和时间
    cursor.insertText(sender);
    cursor.insertText(" (");
    cursor.insertText(QDateTime::currentDateTime().toString("hh:mm:ss"));
    cursor.insertText("): ");

    cursor.insertText(message);
    ui->MessageEdit->ensureCursorVisible(); // 确保光标可见，以便滚动到底部
}

void GroupChat::onError(QAbstractSocket::SocketError error)
{
    QString errorString;
    switch (error)
    {
        case QAbstractSocket::ConnectionRefusedError:
                errorString = "连接被拒绝";
                break;
         case QAbstractSocket::RemoteHostClosedError:
                errorString = "远程主机关闭了一个现有的连接";
                break;
         default:
                errorString = "未知错误";
     }
            qDebug() << "发生错误：" << errorString;


     if (currentReconnectAttempt < maxReconnectAttempts)
     {
          qDebug() << "发生错误：" << error << "，正在尝试重新连接...";
          currentReconnectAttempt++; // 增加重连尝试次数
          QTimer::singleShot(5000, this, &GroupChat::reconnect); // 5秒后尝试重连
     }
     else
     {
         qDebug() << "达到最大重连尝试次数，停止重连。";
         // 可以在这里添加其他错误处理逻辑，例如显示错误信息给用户
     }
}

void GroupChat::reconnect()
{
    socket->abort(); // 断开当前连接
    socket->connectToHost("192.168.1.45", 8080); // 重新连接到服务器
}

// 用户列表
void GroupChat::updateUserList(const QString &message)
{
    QStringList userList = message.mid(QString("USERLIST:").length()).split(",");
    ui->UserListWidget->clear();
    ui->UserListWidget->addItems(userList);
}
